<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 金钻 ajie
 */
class JinzuanController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );



        switch($this->config['paytype']){
            //微信
            case 1:
            //微信H5
            case 2:
                $pay_bankcode = 'WechatPay';
                break;

            //支付宝
            case 3:
            case 17: //原生
            case 4:
            case 18: //原生
                $pay_bankcode = 'AliPay';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $native = array(
            "merchantId" => $this->config['mch_id'],
            "timestamp" => getMillisecond() ,
            "signatureMethod" => 'HmacSHA256',
            "signatureVersion" => 1 ,
        );

        $body = array(
            "jUserId" => md5('wlf'.$array['userid']),
            "jUserIp" => getIP() ,
            "jOrderId" => $return['orderid'],
            "orderType" => 1 ,
            "payWay" => $pay_bankcode,
            "amount" => number_format($return['amount'],2,'.',''),
            "currency" => 'CNY',
            "jExtra" => 'wlf' ,
            "notifyUrl" => $return['notifyurl']
        );


        $native1 = array_merge($native,$body);
        $native['signature'] = $this->createSign1($native1,$this->config['signkey']);

        $url = '?'.http_build_query($native);
        $res = curl($this->config['gateway'].$url, httpstr($body));

       //var_dump('<pre/>',$this->config['gateway'].$url,$body,$native,$this->config['signkey'],$res);exit();


        $resp = json_decode($res,true);

        $code = $resp['data']['paymentUrl'];

        if(!$code){
            if($resp['message']){
                $this->showmessage($resp['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");

    }


    public function createSign1($array, $secretKey){
        //倒序排序
        ksort($array);
        //以&拼接参数 返回处理 链接特殊符号
        $req_params2 = urldecode(http_build_query($array));
        //加密处理，转大写
        $req_signature =  strtoupper(hash_hmac('sha256', $req_params2, $secretKey, false));
        return $req_signature;
    }



    //通知
    public function notifyurl(){
        //$this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['148.66.11.72'])){
            exit("wrong");
        }

        //$p = json_decode(file_get_contents('php://input'),true);
        $p = I("post.");

        $g = I("get.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['jOrderId'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
             "pay_orderid_rd"=>htmlspecialchars($p['orderId'])
        ));


        $real_amount =  $p['actualAmount'];     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $sign = $g['signature'];
        unset($g['signature']);

        $native1 = array_merge($g,$p);
        $sign2 = $this->createSign1($native1,$this->config['signkey']) ;

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['status'] !== '2' && $p['status'] !== '3'  ){
            exit("fail");
        }

        $data = [
                'code'=>0,
                'message'=>'ok',
                'data'=>[],
                ];

        $this->async($find['pay_orderid'],json_encode($data));
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
